import { onUnmounted } from 'vue'
import useHotKey from './hotKeys'
import { useFullscreen } from '@vueuse/core'
// const downKeysList = new Set()
const { isFullscreen } = useFullscreen()
let isFirst = true
// let keyTimer = null
export function useBroad() {
  let p2p = null
  let remoteId = null
  const ele = document
  // 转化左右相同按键的code
  const sendMessage = (event, flag) => {
    let { code, key, keyCode } = event
    if (code == 'ControlRight') {
      keyCode = 163
    } else if (code == 'ControlLeft') {
      keyCode = 162
    } else if (code == 'ShiftLeft') {
      keyCode = 160
    } else if ((key == 'Shift' && code == '') || code == 'ShiftRight') {
      keyCode = 161
    } else if (code == 'AltLeft') {
      keyCode = 164
    } else if (code == 'AltRight') {
      keyCode = 165
    } else if (code == 'MetaLeft') {
      keyCode = 91
    } else if (code == 'MetaRight') {
      keyCode = 92
    }
    const params = {
      endpointType: 1,
      events: [
        {
          eventType: 'keyboard',
          timestamp: Math.floor(new Date().getTime() / 1000) + '',
          eventData: JSON.stringify({
            flag,
            code: keyCode
          })
        }
      ]
    }
    // 初次需要同步casp，num，scrolll按键状态
    if (isFirst) {
      let is_caps_locked = false,
        is_num_locked = false,
        is_scroll_locked = false
      if (event.getModifierState('CapsLock')) {
        is_caps_locked = true
      } else {
        is_caps_locked = false
      }

      if (event.getModifierState('NumLock')) {
        is_num_locked = true
      } else {
        is_num_locked = false
      }

      if (event.getModifierState('ScrollLock')) {
        is_scroll_locked = true
      } else {
        is_scroll_locked = false
      }
      const params = {
        endpointType: 1,
        events: [
          {
            eventType: 'keyboard_status',
            timestamp: new Date().getTime() + '',
            // timestamp: Math.floor(new Date().getTime() / 1000) + '',
            eventData: JSON.stringify({
              is_caps_locked,
              is_num_locked,
              is_scroll_locked
            })
          }
        ]
      }
      p2p && p2p.send(remoteId, JSON.stringify(params))
      isFirst = false
    }
    p2p && p2p.send(remoteId, JSON.stringify(params))
  }

  /**
   * 处理未发送的按键事件(异常卡键)，在全屏模式和域名访问下，不会出现卡键问题
   */
  // const checkKeys = () => {
  //   if (downKeysList.size > 0) {
  //     ;[...downKeysList].forEach((item) => {
  //       sendMessage(item, 0)
  //       downKeysList.delete(item)
  //     })
  //   }
  // }

  /**
   * 监听键盘按下事件, 对全屏快捷键进行处理，对esc键解除鼠标锁定
   * 进入全屏屏蔽所有浏览器按键
   */
  const addKeyDown = (event) => {
    event.preventDefault()
    if (event.keyCode === 27 && isFullscreen.value) {
      if (
        document.pointerLockElement ||
        document.mozPointerLockElement ||
        document.webkitPointerLockElement
      ) {
        document.exitPointerLock()
      }
    }
    // clearTimeout(keyTimer)
    // downKeysList.add(event.keyCode)
    // keyTimer = setTimeout(checkKeys, 1000)
    sendMessage(event, 4)
  }

  // 监听键盘弹起事件
  const addKeyUp = (event) => {
    // if (downKeysList.has(keyCode)) {
    //   downKeysList.delete(keyCode)
    // }
    sendMessage(event, 0)
  }

  const addBroadEvent = (p2pObj, id) => {
    // console.log('监听键盘事件...')
    p2p = p2pObj
    remoteId = id
    ele.addEventListener('keydown', addKeyDown)
    ele.addEventListener('keyup', addKeyUp)
  }
  const removeBroadEvent = () => {
    ele.removeEventListener('keydown', addKeyDown)
    ele.removeEventListener('keyup', addKeyUp)
  }

  const autoKey = [
    'ctrl+w',
    'ctrl+t',
    'ctrl+n',
    'ctrl+tab',
    'ctrl+shift+tab',
    'ctrl+shift+n',
    'ctrl+f5',
    'f5',
    'ctrl+r',
    'ctrl+f',
    'ctrl+f1',
    'ctrl+f2',
    'ctrl+1',
    'ctrl+2'
  ]
  useHotKey(autoKey.join(','), (event) => {
    console.log('监听浏览器默认快捷键...')
    event.preventDefault()
  })

  // 移除键盘监听事件
  onUnmounted(() => {
    try {
      removeBroadEvent()
    } catch (err) {
      console.log(err)
    }
  })

  return { addBroadEvent, removeBroadEvent }
}
